<?php

namespace console\controllers;
use console\server\SwooleYiiApplication;
use console\server\YiduHttpServer;
use console\server\YiduTcpServer;
use yii\console\Controller;

class SwooleServerController extends Controller {

	private $tcpserver;
	private $httpserver;
	private $app;
	private $baselogpath = "/tmp/swoole/";

	public function __construct() {

		$this->app = new SwooleYiiApplication();
		$this->startTcpServer();
		$this->startHttpServer();

	}

	private function startTcpServer() {
		//ok start server
		$tcp_port=\Yii::$app->params['tcp_server_port'];
		$this->tcpserver = new YiduTcpServer("0.0.0.0", $tcp_port);
		$this->tcpserver->setApp($this->app);
		$this->tcpserver->configure(array(
			'tcp' => array(
				'reactor_num' => 4,
				'worker_num' => 4,
				'task_worker_num' => 8,
				'daemonize' => 1,
				'max_request' => 10000,
				'dispatch_mode' => 2,
				'debug_mode' => 1,
				'log_file' => $this->baselogpath . "sw_server.log",
			),
			'dora' => array(
				'pid_path' => $this->baselogpath, //dora 自定义变量，用来保存pid文件
			),
		));

		$this->tcpserver->start();
	}

	private function startHttpServer() {
		$http_port=\Yii::$app->params['http_server_port'];
		$this->httpserver = new YiduHttpServer("0.0.0.0", $http_port);
		$this->tcpserver->setApp($this->app);
		$this->httpserver->configure(array(
			'http' => array(
				//to improve the accept performance ,suggest the number of cpu X 2
				//如果想提高请求接收能力，更改这个，推荐cpu个数x2
				'reactor_num' => 4,
				//packet decode process,change by condition
				//包处理进程，根据情况调整数量，推荐cpu个数x2
				'worker_num' => 4,
				//the number of task logical process progcessor run you business code
				//实际业务处理进程，根据需要进行调整
				'task_worker_num' => 8,
				'daemonize' => 1,
				'log_file' => $this->baselogpath . 'sw_http_server.log',
				'task_tmpdir' => $this->baselogpath . '/http/swtasktmp/',
			),
			'dora' => array(
				'pid_path' => $this->baselogpath, //dora 自定义变量，用来保存pid文件
				'log_path' => $this->baselogpath . 'bizlog_http/', //业务日志
			),
		));

		//redis for service discovery register
		//when you on product env please prepare more redis to registe service for high available
		//暂时不进行服务注册
		//$server->discovery(['group1', 'group2'], [[["ip" => "127.0.0.1", "port" => "6379"], ["ip" => "127.0.0.1", "port" => "6379"]]]);
		$this->httpserver->start();
	}

}